<script setup lang="ts">
import { ref, watch } from 'vue';
import { buildTree } from '@/renderer/utils/helper';

const emits = defineEmits(['handleOk',])

const visibal = ref(false)
const originalNote = ref({})
const openModal = (note: any) => {
    originalNote.value = note
    getList().then(res => {
        treeData.value = res as any
    })
    visibal.value = true
}

watch(() => visibal.value, (val) => {
    if (!val) {
        selectedKeys.value = []
    }
})

const handleOk = () => {
    emits('handleOk', selectedKeys.value[0] ?? "");
    visibal.value = false
}

defineExpose({
    openModal
})

const selectedKeys = ref<string[]>([]);
const treeData = ref<any[]>([]);
const noteList = ref<any[]>([])
const getList = async () => {
    return new Promise(async (resolve) => {
        try {
            // 通过Express API获取笔记数据
            const response = await fetch('http://localhost:32068/api/memorys');
            const result = await response.json();
            
            // 使用API返回的数据
            if (result.data && Array.isArray(result.data)) {
                noteList.value = result.data;
            } else {
                noteList.value = [];
            }
        } catch (error) {
            console.error("通过API获取笔记数据失败:", error);
            noteList.value = [];
        }

        let sortedNoteList = noteList.value.sort((a: { created: string | number | Date; }, b: { created: string | number | Date; }) => {
            return new Date(b.created).getTime() - new Date(a.created).getTime();
        });
        sortedNoteList = sortedNoteList.filter((note: { isFolder: any; }) => note.isFolder).map((note: { id: any; key: any }) => {
            note.key = note.id.toString();
            return note;
        });
        const NoteTree = buildTree(sortedNoteList) ?? []
        resolve(extractOneself(NoteTree, originalNote.value))
    })

};


const extractOneself = (NoteTree: any, Node: { id?: any; }) => {
    // 从 NoteTree 树中找到 Node 节点，去除 Node 节点以及其子节点， 返回剩余的树结构
    // 深拷贝树结构，避免修改原树
    const treeCopy = JSON.parse(JSON.stringify(NoteTree));
    // 递归函数用于移除指定节点及其子节点
    const removeNode = (nodes: any[]) => {
        return nodes.filter((node: { id: any; children: any[]; }) => {
            // 如果当前节点是目标节点，移除它
            if (node.id === Node.id) {
                return false;
            }
            // 如果当前节点有子节点，递归处理子节点
            if (node.children && node.children.length > 0) {
                node.children = removeNode(node.children as any[]);
            }
            return true;
        });
    };

    return removeNode(treeCopy);
}

</script>

<template>

    <a-modal v-model:open="visibal" title="可移动文件夹" style="width: 45%;" :maskClosable="false" :destroyOnClose="true"
        :footer="false">
        <div class="folder-wrapper">
            <a-tree v-if="treeData.length > 0" :defaultExpandAll="true"
                :fieldNames="{ children: 'children', title: 'title', key: 'id' }" v-model:selectedKeys="selectedKeys"
                :tree-data="treeData">
                <template #title="{ data }">
                    <span>
                        <span class="iconfont icon-wenjianjia" style="color:#ffbf00;"></span>
                        {{ data.title }}
                    </span>
                </template>
            </a-tree>
            <div v-else style="font-size: 13px;color: rgb(153, 153, 153);padding-top: 20px;">
                暂无可移动文件夹~
            </div>
        </div>
        <div style="text-align: right;padding-top: 20px;">
            <a-button @click="visibal = false">取消</a-button>
            <a-button type="primary" @click="handleOk" style="margin-left: 10px;">保存</a-button>
        </div>
    </a-modal>

</template>

<style scoped>
.folder-wrapper {
    display: flex;
    flex-direction: column;
    min-height: 200px;
    padding: 20px 15px;
    background-color: var(--surface-color);
    border-radius: var(--border-radius);
    border: 1px solid var(--border-color);
}

.folder-tree {
    background-color: var(--surface-color);
    border-radius: var(--border-radius);
}

.folder-tree .ant-tree-treenode {
    padding: 4px 0;
}

.folder-tree .ant-tree-node-content-wrapper {
    border-radius: var(--border-radius);
    transition: var(--transition);
}

.folder-tree .ant-tree-node-content-wrapper:hover {
    background-color: var(--primary-color);
    color: white;
    transform: translateY(-1px);
    box-shadow: var(--shadow);
}

.folder-tree .ant-tree-node-selected {
    background-color: var(--primary-color) !important;
    color: white;
}

.folder-tree .ant-tree-node-selected:hover {
    background-color: var(--primary-hover-color) !important;
    transform: translateY(-2px);
    box-shadow: var(--shadow-hover);
}

.no-folder {
    font-size: 13px;
    color: var(--text-placeholder);
    padding-top: 20px;
    text-align: center;
}

.modal-footer {
    text-align: right;
    padding: 15px;
    background-color: var(--surface-color);
    border-top: 1px solid var(--border-color);
    border-radius: 0 0 var(--border-radius) var(--border-radius);
}

.btn-cancel {
    margin-right: 10px;
    border-radius: var(--border-radius);
    border: 1px solid var(--border-color);
    background-color: var(--surface-color);
    color: var(--text-primary);
    transition: var(--transition);
}

.btn-cancel:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
}

.btn-save {
    border-radius: var(--border-radius);
    border: 1px solid var(--primary-color);
    background-color: var(--primary-color);
    color: white;
    transition: var(--transition);
}

.btn-save:hover {
    background-color: var(--primary-hover-color);
    border-color: var(--primary-hover-color);
    box-shadow: var(--shadow);
}
</style>